package ewa

import (
	"fmt"
	"github.com/labstack/echo"
)

func UseAuth() {
    l:=fmt.Sprintf("-Sqlite3/> authentication database file: '%s'", CfgAuth.SL3File);Log(l)
    db := SQLite3_Open_DBfile(CfgAuth.SL3File)
    SQLite3_AuthTab_Create(db,  CfgAuth.SL3Table)
    SQLite3_Close(db)
}

func UserAvail(user string) bool {
    db := SQLite3_Open_DBfile(CfgAuth.SL3File)
    cnt,_ := SQLite3_AuthTab_QueryUser(db, CfgAuth.SL3Table, user)
    SQLite3_Close(db)
    if cnt == 0 {
        return false
    }else if cnt > 0 {
        return true
    }
    return false
}

func FetchPass(user string) string {
    db := SQLite3_Open_DBfile(CfgAuth.SL3File)
    Pass,_ := SQLite3_AuthTab_QueryPassword(db, CfgAuth.SL3Table, user)
    SQLite3_Close(db)
    return Pass
}

func UserAuthSuccess(c echo.Context) bool {
    //获取POST Form, Username;Password的值
    Username := c.FormValue("Username")
    Password := c.FormValue("Password")

    if UserAvail(Username) != true {
    	l:=fmt.Sprintf("Userauth/> '%s' don't exsit!", Username)
    	Log(l)
    	return false
    }
    if FetchPass(Username) != Password {
    	l:=fmt.Sprintf("Userauth/> '%s' password wrong!", Username)
    	Log(l)
    	return false
    } else {
    	return true
    }

}

func UserAdd(c echo.Context) bool {

    db := SQLite3_Open_DBfile(CfgAuth.SL3File)
    _,cnt,_ :=SQLite3_AuthTab_InsertNew(db, CfgAuth.SL3Table, 
        DefaultUser(c.FormValue("user"),c.FormValue("pass")))
    SQLite3_Close(db)
    
    if cnt == 0 {
        return false
    }else{
        return true
    }

}

func UserChangePass(c echo.Context) bool {
    db := SQLite3_Open_DBfile(CfgAuth.SL3File)
    pass,_ :=SQLite3_AuthTab_QueryPassword(db, CfgAuth.SL3Table, c.FormValue("user")) 
    if pass != c.FormValue("pass") {
        return false
    }

    cnt,_ := SQLite3_AuthTab_UpdatePassword(db, CfgAuth.SL3Table, c.FormValue("user"), c.FormValue("newpass"))
    if cnt == 0{
        return false
    }

    SQLite3_Close(db)
    
    return true    

}